iT邦幫忙

2022 iThome 鐵人賽

DAY 17
0
Software Development

30而Leet{code}系列 第 17

D17 - [Linked List] Reverse Linked List

  • 分享至 

  • xImage
  •  

問題很簡單,就是反轉一個 Linked List.

問題

https://leetcode.com/problems/reverse-linked-list/

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:
Input: head = [1,2]
Output: [2,1]

Example 3:
Input: head = []
Output: []

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

複習

在 Go 語言,每個變數都要有對應的資料格式,通常我們會使用類型推斷(Type Inference)來宣告變數並給予初始值,譬如:message := "Hello World"
但如果要宣告一個變數為 nil 值時,則無法使用Type Inference.
所以這個語法previous := nil是錯誤的.
必須將對應的資料格式一起宣告 var previous *ListNode = nil

我的答案

使用三個指標:

  • head: 下一個節點(也可以令外宣告一個 next 指標,但為了節省記憶體,直接用現成的 head 指標.
  • current: 目前的節點
  • previous: 前一個節點

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        previous = None
        current = head
        while current:
            head = head.next
            current.next = previous
            previous = current
            current = head
        return previous

Go

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */ 
func reverseList(head *ListNode) *ListNode {
    var previous *ListNode = nil
    var current *ListNode = head
    for current != nil {
        head = head.Next
        current.Next = previous
        previous = current
        current = head
    }
    return previous
}

上一篇
D16 - [Linked List] Delete the Middle Node of a Linked List
下一篇
D18 - [Linked List] Partition List
系列文
30而Leet{code}30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言